import 'dart:convert';
import 'package:get/get.dart';
import 'package:wk_robot2/app/event/DataCallBack.dart';
import 'package:wk_robot2/app/logger/Logger.dart';
import 'package:wk_robot2/app/modules/bindtip/views/bindtip_view.dart';
import 'package:wk_robot2/app/nets/NetWorkManager.dart';
import 'package:wk_robot2/app/routes/app_pages.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';
import '../../../blt/RobotCommandsHelper.dart';
import '../../../blt/protobuf/BleBindOrSwitchWifi.pb.dart';
import '../../../const/AppConst.dart';
import '../../../event/WkEventListener.dart';
import '../../../models/WifiInfo.dart';
import '../../../robot_comm/mqtt_comm_manager.dart';
import '../../../storage/StorageManager.dart';
import '../../../widget/CommonWidgets.dart';
import '../../../widget/tips.dart';
import '../../componentview/controllers/IndexViewController.dart';

class BindingController extends GetxController {

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();

    /*if (wifiInfo != null) { // 需要给机器人配网.
        RobotCommandsHelper().configWifiList(wifiInfo!.c!, wifiInfo!.s!, wifiInfo!.getPw(), DataCallBack(
          deviceCallBack: (data) {
               print('开始配置wifi');
               BindOrSwitchWifiResponse wifiResponse = BindOrSwitchWifiResponse.fromBuffer(data[AppConst.BTL_DATA_KEY] as List<int>);
               print('wifi配置结果, ${wifiResponse.data}');
               Map wifiRepsonse = json.decode(wifiResponse.data);
               if(wifiRepsonse['co'] == 102) { //wifi联网成功.
                 print('============> wifi联网成功');
                 //绑定机器人.
                 bindFinal();

               } else { //联网失败.
                  *//*CommonWidgets.showSingleBtnDialog(Get.context!, '提示', '机器人配网失败,返回上一步重新操作.', WkEventListener(
                      onClick: (v) {
                        Get.back();
                      }
                  ));*//*
                  Get.toNamed(Routes.BINDTIP,arguments: {
                    'type': NET_WORK_CONFIG_FAILURE
                  });

               }
          }
        ));
    } else { //如果机器人本身已经有网络,则直接进行绑定.
      bindFinal();
    }*/

    bindFinal();
  }


  void bindFinal() {
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.BIND_ROBOT_TO_USER, {
      'serialNumber': CommonUtil.getBltDeviceTmpSN()
    }, NetWorkManager.methodPOST, DataCallBack(
        businessCallBack: (v) {
          //todo 机器人序列号不存在.

          print('============> 完成机器人绑定');

          StorageManager.getStorage().write(AppConst.BLT_DEVICE_ROBOTE_TOKEN, v);
          // 获取机器人的AgentToken.
          String uagentToken = v['uagentToken'];
          String uagentRefreshToken = v['uagentRefreshToken'];

          RobotCommandsHelper().sendBindResultAndAgent2Robot(true, uagentToken, uagentRefreshToken, DataCallBack(
              deviceCallBack: (robotV) {
                BindOrSwitchWifiResponse robotTokenResponse  = BindOrSwitchWifiResponse.fromBuffer(robotV[AppConst.BTL_DATA_KEY] as List<int>);
                print('============> 完成机器人Token设置. ${robotTokenResponse.data}');
                Map bindAndRendAgent = json.decode(robotTokenResponse.data);

                if (bindAndRendAgent['co'] == 109) {
                  Tips.showToast('绑定成功.');
                  // 把临时SN码转正.
                  String tempSN = CommonUtil.getBltDeviceTmpSN();
                  StorageManager.getStorage().write(AppConst.BLT_DEVICE_SN_CURRENTLY,tempSN);

                  IndexViewController indexViewController = GetInstance().find<IndexViewController>();
                  if (indexViewController != null) {
                    indexViewController.retrieveRobots(fromBindPage:true);

                  }



                  // Get.offAllNamed(Routes.HOME);
                  Get.toNamed(Routes.BIND_SUCESS);
                } else {
                  // 把临时SN码转正.
                  String tempSN = CommonUtil.getBltDeviceTmpSN();
                  StorageManager.getStorage().write(AppConst.BLT_DEVICE_SN_CURRENTLY,tempSN);

                  logger.info('绑定结果: ${robotTokenResponse.data}');

                  IndexViewController indexViewController = GetInstance().find<IndexViewController>();
                  if (indexViewController != null) {
                    indexViewController.retrieveRobots(fromBindPage:true);

                  }
                  Get.toNamed(Routes.BIND_SUCESS);
                  // Get.offAllNamed(Routes.HOME);
                }

              }
          ));
        },
        errorCallBack: (v) {
           logger.info('序列号不存在...');
           Get.toNamed(Routes.BINDTIP,arguments: {
             'type': DEVICE_SN_NO_EXISTANCE,
             'robotUserId': CommonUtil.getBltDeviceTmpSN()
           });
        }
    ));
  }

  @override
  void onClose() {
    super.onClose();
  }
}
